package com.ccx.coachsite.ui.softmgr;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ccx.coachsite.R;
import com.ccx.coachsite.api.CoachSiteSoftMgrApiAccessor;
import com.ccx.coachsite.downloadmgr.DownloadTool;
import com.ccx.coachsite.model.ServerDetailResult;
import com.ccx.coachsite.model.ServerResult;
import com.ccx.coachsite.model.SoftShareMessage;
import com.ccx.coachsite.model.SoftTopicItem;
import com.ccx.coachsite.ui.login.LoginHelper;
import com.ccx.coachsite.util.OpenShareTool;

public class SoftMgrTopicWebDetail extends Activity {

	private WebView webContent;
	private TextView login_top_title;
	private ImageButton btn_back;
	private String topicName,topicID,topicURL;
	private Button btnDownload, btnShare, btnBack;
	
	private ProgressBar webProgressBar;
	private View llOnLoadingView;
	private View llOnDetailView;
	
	private int iSoftID;
	
	/**专题应用下载地址消息*/
	private static final int MESSAGE_TOPIC_LIST_DOWN = 1;
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MESSAGE_TOPIC_LIST_DOWN:
					Object[] objs = (Object[]) msg.obj;
					if (null == objs){
						return;
					}
					
					Integer objSoftID = (Integer)objs[0];
					if (objSoftID!=null){
						iSoftID = objSoftID.intValue();
						btnDownload.setVisibility(View.VISIBLE);
					}
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.soft_mgr_soft_topic_webview);
		
		//专题列表显示返回导航
		topicName = (String)getIntent().getStringExtra("TopicName" );
		topicID = (String)getIntent().getStringExtra( "TopicID" );
		topicURL = (String)getIntent().getStringExtra( "TopicURL" );
		
		llOnLoadingView = findViewById(R.id.ll_on_loading);
		llOnDetailView =  findViewById(R.id.ll_on_detail);
		llOnLoadingView.setVisibility(View.GONE);
		
		//llOnLoadingView.setVisibility(VISIBLE);
		//llOnDetailView.setVisibility(GONE);
		
		webProgressBar = (ProgressBar) findViewById(R.id.toturial_web_progress_bar);
		
		webContent = (WebView) findViewById(R.id.tutorial_detail_content);
		webContent.getSettings().setJavaScriptEnabled(true);
		//设置WebView支持下载
		webContent.setDownloadListener(new MyWebViewDownLoadListener());
		
		webContent.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				webProgressBar.setProgress(progress);
				if (progress >= 100)
					webProgressBar.setVisibility(View.GONE);
				else
					webProgressBar.setVisibility(View.VISIBLE);
			}
		});
		webContent.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				boolean result = true;
				webContent.loadUrl(url);
				return result;
			}
		});
		
		if (topicURL==null){
			ServerDetailResult<SoftTopicItem> topicItem = CoachSiteSoftMgrApiAccessor.getSoftMgrTopicDetail(topicID);
			if ( topicItem.detailItem!=null){
				topicName = topicItem.detailItem.getName();
				topicURL  = topicItem.detailItem.getDetails();
			}else{
				topicName = "";
				topicURL = "";
			}
		}
		
		webContent.loadUrl(topicURL);
		
		btnDownload = (Button) findViewById(R.id.tutorial_button_download);
		btnDownload.setOnClickListener(btnDownloadOnClickListener);
		
		btnShare = (Button) findViewById(R.id.tutorial_button_share);
		btnShare.setOnClickListener(btnShareOnClickListener);
		btnShare.setText(OpenShareTool.getShareDesc(SoftMgrTopicWebDetail.this));
		
		btnBack = (Button) findViewById(R.id.tutorial_detail_back);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (webContent.canGoBack())
					webContent.goBack();
			}
		});
		
		login_top_title = (TextView)findViewById(R.id.login_top_title);
	  	login_top_title.setText(topicName);
	  	login_top_title.setSelected(true);
	  	
	  	btn_back=(ImageButton)findViewById(R.id.login_btn_return);
	  	btn_back.setOnClickListener(new View.OnClickListener() {
		
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	  	
	  	checkTopicDown();
	  	
	    //添加分享点击统计
		int iShareMsgID = getIntent().getIntExtra("ShareCount", -1);
		if (iShareMsgID!=-1){
			CoachSiteSoftMgrApiAccessor.execShareMsgCount(iShareMsgID);
		}	  	
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webContent.canGoBack()) {
				webContent.goBack();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	
	@Override
	protected void onResume() {
		super.onResume();
		
		btnShare.setText(OpenShareTool.getShareDesc(SoftMgrTopicWebDetail.this));
	}
	
	OnClickListener btnShareOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (!LoginHelper.requireLogin(SoftMgrTopicWebDetail.this))
				return;

			OpenShareTool.showOperDialog(SoftMgrTopicWebDetail.this,topicName, "", topicID+ "", SoftShareMessage.TYPE_TOPIC_SHARE_TYPE,
					"专题", DownloadTool.SOFT_FLAG_DEFALUT_VALUE);
		}
	};
	
	OnClickListener btnDownloadOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			DownloadTool.downSoftItemByID(SoftMgrTopicWebDetail.this, iSoftID);
		}
	};
	
	private void checkTopicDown() {

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					//下载列表数据
					String urlStr = CoachSiteSoftMgrApiAccessor.API_SOFTMGR_TOPIC_APP_LIST+topicID
							+"?"+CoachSiteSoftMgrApiAccessor.PAGE_NUMBER+"=1";
					ServerResult<SoftInfo> result =  CoachSiteSoftMgrApiAccessor.getSoftAppList(urlStr);
					int softIdObj = 0;
					if (result.itemList!=null && result.itemList.size()>0){
						String sid = result.itemList.get(0).getSid();
						softIdObj = Integer.parseInt(sid);
						
						//发送更新
						Message msg = handler.obtainMessage(MESSAGE_TOPIC_LIST_DOWN,new Object[] { softIdObj });
						msg.sendToTarget();
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	private class MyWebViewDownLoadListener implements DownloadListener {

		@Override
		public void onDownloadStart(String url, String userAgent,
				String contentDisposition, String mimetype, long contentLength) {
			Uri uri = Uri.parse(url);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}
	}

}
